﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;

namespace Colorful.Furniture;

public class Program
{
    public static async Task<int> Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("System", LogEventLevel.Error)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Error)
            .Enrich.FromLogContext()
            .WriteTo.Async(c => c.File(
                path: "logs/logs.txt",
                rollingInterval: RollingInterval.Day,
                rollOnFileSizeLimit: false,
                flushToDiskInterval: TimeSpan.FromSeconds(2)))
#if DEBUG
            .WriteTo.Async(c => c.Console())
#endif
            .CreateLogger();

        try
        {
            Log.Information("Starting Colorful.Furniture.HttpApi.Host.");
            var builder = WebApplication.CreateBuilder(args);
            builder.Host
                .AddAppSettingsSecretsJson()
                .UseAutofac()
                .UseSerilog();
            //设置请求体的最大值
            builder.WebHost.ConfigureKestrel((_, options) =>
            {
                //设置最大1G, 这里的单位是byte
                options.Limits.MaxRequestBodySize = 10737418240;
            });
            await builder.AddApplicationAsync<FurnitureHttpApiHostModule>();
            var app = builder.Build();
            GlobalServiceScopeFactory.Instance = app.Services.GetRequiredService<IServiceProvider>();
            await app.InitializeApplicationAsync();
            await app.RunAsync();
               
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly!");

            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}
